<?php


namespace app\admin\controller;


use app\common\model\Options;
use think\Controller;
use app\common\model\Project as ProjectModel;
use app\common\model\User as UserModel;

class ProjectController extends Controller
{

    protected $loginRquire = true;


    protected $beforeActionList = [
        '_before_index' => ['only'=>'index'],  // 注意不要有空格
        '_before_update' => ['only'=>'update'],
        '_before_delete' => ['only'=>'delete'],
    ];


    protected function _before_index()
    {
        echo "before index";
    }


    protected function _before_update()
    {
        if ($this->request->isGet()){
            $project_id = $this->request->get('id');
        }else{
            $postData = $this->request->post();
            $project_id = $postData['id'];
        }

        $user_id =session('user_id');
        $user = UserModel::get($user_id);

        // 若没有权限，弹框
        if(!($user->hasPermission($project_id, 'update'))){
            return $this->error('Sorry, 您没有修改权限 !','','',10);
        }
        // print_r("有权限".$project_id);

    }


    protected function _before_delete()
    {
        $project_id = $this->request->get('id');
        $user_id =session('user_id');
        $user = UserModel::get($user_id);

        // 若没有权限，弹框
        if(!($user->hasPermission($project_id, 'delete'))){
            // print_r("没有权限:".$project_id);
            exit(json_encode(['code'=>4003, 'message'=>'没有权限']));
        }
        // print_r("有权限".$project_id);
    }

    public function _initialize()
    {
        if ($this->loginRquire && session('username')) {
            return;
        }

        $this->error('不可访问, 请先登录...', url('admin/login/index'),'', 2);
    }

    /**
     * @param null $uid: user_id .默认null,获取所有项目.
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($uid=null)
    {
        if ($this->request->isGet()) {
            $project = new ProjectModel();
            // if (is_null($uid)){
            //     $projects = $project->select();
            // }else{
            //     $projects = $project->where('person', $uid)->select();
            // }
            $projects = $project->select();

            $tpl_params = [
              'projects'=>$projects,
              'user'=>session('is_super'),
            ];

            $this->assign($tpl_params);
            $html = $this->fetch();
            return $html;
        }

    }

    /**
     * 用于指定用户id，该用户所拥有的项目。
     * @param $uid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index_with_user($uid=null)
    {
        //如果没uid参数，则默认去当前登录用户的id
        if (is_null($uid)){
            $uid = session('user_id');
        }

        if ($this->request->isGet()) {
            $project = new ProjectModel();
            //session获取分配给该用户的项目
            // $permissions = session('permissions');  // 解决bug：在用户列表跳转的开发人员项目列表的时候，一定是admin，而在“我的项目”跳转则是用户本人
            // 数据库动态获取分配给该用户的项目
            $user = UserModel::get($uid);
            $permissions = array();
            foreach ($user->auths as $item) {
                $permissions = json_decode($item['permission'], true);
            }

            // 该用户自己开发的项目 + 管理员分配权限的任务
            $projects = $project->where('person', $uid)->whereOr('pname','in',array_keys($permissions))->select();

            $tpl_params = [
                'projects'=>$projects,
                'user'=>session('is_super'),
            ];

            $this->assign($tpl_params);
            $html = $this->fetch('project/index');
            return $html;
        }

    }


    public function project_show()
    {
        $project_id = $this->request->get('id');
        $project = ProjectModel::get($project_id);

        if (is_null($project)) {
            return json(['code' => 4000, 'message' => '项目不存在']);
        }

        $this->assign('project', $project);
        $html = $this->fetch();
        return $html;
    }


    public function create()
    {
        if ($this->request->isGet()) {
            // if (session('is_super')){       // 超级用户可选所有用户
            //     $users = UserModel::all();
            //     $this->assign('users', $users);
            // }
            // 屏蔽上一段代码，普通用户也可以访问所有人
            $users = UserModel::all();
            $this->assign('users', $users);

            return $this->fetch('project/create');
        }

        $postData = $this->request->post();

        $project = ProjectModel::get(['pname' => $postData['pname']]);
        if (!is_null($project)) {
            return json(['code' => 4000, 'message' => '项目名已存在']);
        }

        $project = new ProjectModel();
        if ($project->allowField(true)->validate(true)->save($postData)) {
            return json(['code' => 0, 'message' => '添加成功']);
        }
        return json(['code' => 4000, 'message' => '添加失败']);
    }


    public function update()
    {
        if ($this->request->isGet()) {
            $project_id = $this->request->get('id');
            $project = ProjectModel::get($project_id);
            if (is_null($project)) {
                return $this->error('项目不存在');
            }
            // 超级用户才显示所有用户
//            if($this->checkSuperUser()){
//                $user = new UserModel();
//                $users = $user->field(['id', 'name'])->select();
//                $this->assign('users', $users);
//            }
            $user = new UserModel();
            $users = $user->field(['id', 'name'])->select();
            $this->assign('users', $users);

            $this->assign('project', $project);
            return $this->fetch('project/update');
        }

        // 提交更新数据
        $project = new ProjectModel();
        $postData = $this->request->post();
        if ($project->allowField(true)->isUpdate(true)->save($postData, ['id' => $postData['id']])) {
            return json(['code' => 0, 'message' => '更新成功']);
        }
        return json(['code' => 4000, 'message' => '更新失败']);
    }

    public function delete()
    {
        $project_id = $this->request->get('id');
        $project = ProjectModel::get($project_id);

        if (is_null($project)) {
            return json_encode(['code' => 4000, 'message' => '该项目不存在']);
        }
        if ($project->delete()) {
            return json_encode(['code' => 0, 'message' => '删除成功']);
        }
        return json_encode(['code' => 4000, 'message' => '删除失败']);
    }

    /**
     * 筛选字段返回查询数据
     * url： filter?ptype=xxx&pname=xxx
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function filter()
    {
        $query_string = $this->request->get();
        // 限制查询的关键字字符串，只能cms、ptype，防止用户直接url带参数访问后台数据库
        foreach ($query_string as $k=>$item) {
            if (!array_key_exists($k, ['cms'=>'', 'ptype'=>''])){
                $this->assign('projects', null);
                return $this->fetch('project/index');
            }
        }

        var_dump($query_string);

        $uid = session('user_id');
        //session获取分配给该用户的项目
        $permissions = session('permissions');
        if (empty($query_string)){
            $projects = null;
        }else{
            if($this->checkSuperUser()){
                $projects = ProjectModel::where($query_string)->select();
            }else{
                $projects = ProjectModel::where($query_string)->where('person', $uid)->select();
            }
        }

        // foreach ($projects as $index => $item) {
        //     var_dump($item->toJson());
        // }

        $this->assign('projects', $projects);
        return $this->fetch('project/index');

    }

    /**
     * 获取所有下拉可选项
     * @return { type }
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_all_options()
    {
        $options = new Options();
        $types = $options->group('type')->field(['type'])->select();

        $all_options = $options->select();

        $item_list= [];
        foreach ($types as $type) {
            $tmp_list = [];
            foreach ($all_options as $k=>$item){
                if ($type['type']==$item['type']){
                    $tmp_list['type'] = $type['type'];
                    $tmp_list['value'][] = ['id'=> $item['id'], 'name'=>$item['name']];
                }
            }
            $item_list[] = $tmp_list;
        }
        // print_r($item_list);
        return $item_list;


    }

    /**检测当前用户是否为管理员
     * @return bool
     */
    private function checkSuperUser()
    {
        if(session('is_super') == '1')
        {
            return true;
        }
        return false;
    }


    public function test()
    {
        $project = ProjectModel::get(20);
        // var_dump($project->user());
        var_dump($project->getPerson());
    }
}